package com.hulk.dryad.admin.service.impl;


import cn.hutool.core.collection.CollUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hulk.dryad.common.component.R;
import com.hulk.dryad.common.constant.CacheConstants;
import com.hulk.dryad.common.constant.CommonConstants;
import com.hulk.dryad.common.constant.enums.MenuType;

import com.hulk.dryad.persistence.entity.SysMenuModel;
import com.hulk.dryad.persistence.entity.SysRoleMenuModel;
import com.hulk.dryad.persistence.entity.tools.MenuTree;
import com.hulk.dryad.persistence.entity.tools.TreeUtil;
import com.hulk.dryad.persistence.mapper.SysMenuMapper;
import com.hulk.dryad.persistence.mapper.SysRoleMenuMapper;

import com.hulk.dryad.admin.service.SysMenuService;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜单权限表 服务实现类
 * </p>
 *
 * @author kim
 * @since 2017-10-29
 */
@Service
@DS("#" + CommonConstants.TENANT_ID)
@RequiredArgsConstructor
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenuModel> implements SysMenuService {

	private final SysRoleMenuMapper sysRoleMenuMapper;

	@Override
	@Cacheable(value = CacheConstants.MENU_DETAILS+"#60s", key = "#roleId", unless = "#result.isEmpty()")
	public List<SysMenuModel> findMenuByRoleId(Integer roleId) {
		return baseMapper.listMenusByRoleId(roleId);
	}

	@Override
	@Cacheable(value = CacheConstants.MENU_DETAILS+"#60s", unless = "#result.isEmpty()")
	public List<SysMenuModel> findAllMenu() {
		return baseMapper.listMenus();
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	@CacheEvict(value = CacheConstants.MENU_DETAILS, allEntries = true)
	public R removeMenuById(Integer id) {
		// 查询父节点为当前节点的节点
		List<SysMenuModel> menuList = this.list(Wrappers.<SysMenuModel>query().lambda().eq(SysMenuModel::getParentId, id));
		if (CollUtil.isNotEmpty(menuList)) {
			return R.failed("菜单含有下级不能删除");
		}

		sysRoleMenuMapper.delete(Wrappers.<SysRoleMenuModel>query().lambda().eq(SysRoleMenuModel::getMenuId, id));
		// 删除当前菜单及其子菜单
		return R.ok(this.removeById(id));
	}

	@Override
	@CacheEvict(value = CacheConstants.MENU_DETAILS, allEntries = true)
	public Boolean updateMenuById(SysMenuModel sysMenu) {
		return this.updateById(sysMenu);
	}

	/**
	 * 构建树查询 1. 不是懒加载情况，查询全部 2. 是懒加载，根据parentId 查询 2.1 父节点为空，则查询ID -1
	 * @param lazy 是否是懒加载
	 * @param parentId 父节点ID
	 * @return
	 */
	@Override
	public List<MenuTree> treeMenu(boolean lazy, Integer parentId) {
		if (!lazy) {
			return TreeUtil.buildTree(
					baseMapper.selectList(Wrappers.<SysMenuModel>lambdaQuery().orderByAsc(SysMenuModel::getSort)),
					CommonConstants.MENU_TREE_ROOT_ID);
		}

		Integer parent = parentId == null ? CommonConstants.MENU_TREE_ROOT_ID : parentId;
		return TreeUtil.buildTree(
				baseMapper.selectList(
						Wrappers.<SysMenuModel>lambdaQuery().eq(SysMenuModel::getParentId, parent).orderByAsc(SysMenuModel::getSort)),
				parent);
	}

	/**
	 * 查询菜单
	 * @param all 全部菜单
	 * @param type 类型
	 * @param parentId 父节点ID
	 * @return
	 */
	@Override
	public List<MenuTree> filterMenu(Set<SysMenuModel> all, String type, Integer parentId) {
		List<MenuTree> menuTreeList = all.stream().filter(menuTypePredicate(type)).map(MenuTree::new)
				.sorted(Comparator.comparingInt(MenuTree::getSort)).collect(Collectors.toList());
		Integer parent = parentId == null ? CommonConstants.MENU_TREE_ROOT_ID : parentId;
		return TreeUtil.build(menuTreeList, parent);
	}

	/**
	 * menu 类型断言
	 * @param type 类型
	 * @return Predicate
	 */
	private Predicate<SysMenuModel> menuTypePredicate(String type) {
		return vo -> {
			if (MenuType.TOP_MENU.getDescription().equals(type)) {
				return MenuType.TOP_MENU.getType().equals(vo.getType());
			}
			// 其他查询 左侧 + 顶部
			return !MenuType.BUTTON.getType().equals(vo.getType());
		};
	}

}
